package me.illtamer.rpc.transport.socket.util;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.rpc.entity.RpcRequest;
import me.illtamer.rpc.enumeration.PackageType;
import me.illtamer.serializer.CommonSerializer;

import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class ObjectWriter {

    private static final int MAGIC_NUMBER = 0x07060507;

    public static void writeObject(OutputStream output, Object object, CommonSerializer serializer) throws IOException {
        output.write(intToBytes(MAGIC_NUMBER));
        if (object instanceof RpcRequest) {
            output.write(intToBytes(PackageType.REQUEST_PACK.getCode()));
        } else {
            output.write(intToBytes(PackageType.RESPONSE_PACK.getCode()));
        }
        output.write(intToBytes(serializer.getCode()));
        byte[] bytes = serializer.serialize(object);
        output.write(intToBytes(bytes.length));
        output.write(bytes);
        output.flush();
    }

    private static byte[] intToBytes(int value) {
        byte[] bytes = new byte[4];
        bytes[0] =  (byte) ((value>>24) & 0xFF);
        bytes[1] =  (byte) ((value>>16) & 0xFF);
        bytes[2] =  (byte) ((value>>8) & 0xFF);
        bytes[3] =  (byte) (value & 0xFF);
        return bytes;
    }

}
